import Cookies from "js-cookie";
import type { User } from "@/types";

const TOKEN_KEY = "access_token";
const REFRESH_TOKEN_KEY = "refresh_token";
const USER_INFO_KEY = "user_info";

// Token相关操作
export function getToken(): string | undefined {
  return Cookies.get(TOKEN_KEY);
}

export function setToken(token: string): void {
  Cookies.set(TOKEN_KEY, token, { expires: 7 }); // 7天过期
}

export function removeToken(): void {
  Cookies.remove(TOKEN_KEY);
}

// Refresh Token相关操作
export function getRefreshToken(): string | undefined {
  return Cookies.get(REFRESH_TOKEN_KEY);
}

export function setRefreshToken(refreshToken: string): void {
  Cookies.set(REFRESH_TOKEN_KEY, refreshToken, { expires: 30 }); // 30天过期
}

export function removeRefreshToken(): void {
  Cookies.remove(REFRESH_TOKEN_KEY);
}

// 用户信息相关操作
export function getUserInfo(): User | null {
  const userInfo = localStorage.getItem(USER_INFO_KEY);
  return userInfo ? JSON.parse(userInfo) : null;
}

export function setUserInfo(userInfo: User): void {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
}

export function removeUserInfo(): void {
  localStorage.removeItem(USER_INFO_KEY);
}

// 清除所有认证信息
export function clearAuth(): void {
  removeToken();
  removeRefreshToken();
  removeUserInfo();
}

// 检查是否已登录
export function isAuthenticated(): boolean {
  const token = getToken();
  return !!token;
}

// 检查是否有权限
export function hasPermission(permission: string): boolean {
  const userInfo = getUserInfo();
  if (!userInfo || !userInfo.roles) {
    return false;
  }

  // 由于roles现在是string[]，基于角色名称进行权限检查
  const hasAdminRole = userInfo.roles.includes("ADMIN");
  const hasUserRole = userInfo.roles.includes("USER");

  // 管理员权限
  const adminPermissions = ["admin:read", "admin:write", "admin:delete"];
  // 用户权限
  const userPermissions = ["user:read", "user:write"];

  if (hasAdminRole && adminPermissions.includes(permission)) {
    return true;
  }

  if (hasUserRole && userPermissions.includes(permission)) {
    return true;
  }

  return false;
}

// 检查是否有角色
export function hasRole(roleName: string): boolean {
  const userInfo = getUserInfo();
  if (!userInfo || !userInfo.roles) {
    return false;
  }

  return userInfo.roles.includes(roleName);
}
